package com.bdqn.tour.servlet.Yml;


import com.bdqn.tour.service.CityService;
import com.bdqn.tour.service.impl.CityServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/AddImg")
@MultipartConfig
public class Addservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String img = "";
        //获取上传的图片
        Part imgpart = req.getPart("img");
        //获取文件名
        String filename = imgpart.getSubmittedFileName();
        //获取文件后缀
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        //新文件名
        String newFileName = UUID.randomUUID() + fileSuffix;
        //创建文件对象
        String filePath = "C:\\AppData";
        //写入文件
        imgpart.write(filePath + File.separatorChar + newFileName);
        img = newFileName;
        //添加图片
        CityService cityService = new CityServiceimpl();
        int row = cityService.Addimg(img);
        if (row == 1) {
            System.out.println("成功");
        }
    }
}
